#include "lyricsReader.h"
#include "track.h"
#include "lyricswindow.h"

#include <QSettings>
#include <QFile>
#include <QTextStream>
#include <QTextBlock>
#include <QTime>
#include <QDebug>

LyricsReader::LyricsReader(QWidget *parent) :
        QTextEdit(parent)
{
    setReadOnly(true);
    setContextMenuPolicy(Qt::NoContextMenu);

}

void LyricsReader::trackChanged(Track *track)
{
    QSettings settings;
    const QString lyricsDir = settings.value("lyricsDir").toString();

    QStringList extensions;
    extensions << "lrc" << "txt";
    QString lyricsPath;
    foreach (QString extension, extensions) {
        lyricsPath = QString("%1/%2 - %3.%4")
                     .arg(lyricsDir)
                     .arg(track->getArtist())
                     .arg(track->getTitle())
                     .arg(extension);
        if (QFile::exists(lyricsPath))
            break;
    }

    QFile lyricsFile(lyricsPath);

    clear();
    lyrics.clear();
    if (lyricsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {

        QTextStream in(&lyricsFile);
        while (!in.atEnd()) {
            QString line = in.readLine();
            processLine(line);
        }
        lyricsFile.close();

        QMapIterator<double, QString> i(lyrics);
        while (i.hasNext()) {
            i.next();
            QTime timePosition;
            timePosition = timePosition.addMSecs(i.key() * 1000);
            append(i.value());
            setAlignment(Qt::AlignHCenter);
        }

    } else {
        append("No lyrics found for this track.");
        setAlignment(Qt::AlignHCenter);
    }


    emit lyricsLoaded(track);
}

void LyricsReader::processLine(QString line)
{
    QRegExp rx;
    rx.setPattern("(\\[(\\d{2}):(\\d{2}(?:\\.\\d{2})?)\\])");

    QList<double> timePositions;

    int pos = 0;
    int lastPos = 0;
    while ((pos = rx.indexIn(line, pos)) != -1) {
        int minutes = rx.cap(2).toInt();
        double seconds = rx.cap(3).toDouble();

        double timePosition = minutes * 60 + seconds;
        timePositions << timePosition;

        pos += rx.matchedLength();
        lastPos = pos;
    }
    if (timePositions.count() > 0) {
        QString lyric = line.mid(lastPos);
        foreach(double timePosition, timePositions) {
           lyrics.insert(timePosition, lyric);
       }
    }
}

int LyricsReader::getLyricNumber(double time)
{
    QMap<double, QString>::iterator i = lyrics.upperBound(time);
    i--;
    double upperValue = i.key();
    return lyrics.keys().indexOf(upperValue);
}

void LyricsReader::positionChanged(double time)
{
    int blockNumber = getLyricNumber(time);

    QTextBlock textBlock = document()->findBlockByNumber(blockNumber);
    QTextCharFormat format;

    QTextCursor oldCursor = textCursor();
    oldCursor.select(QTextCursor::Document);

    format.setFontWeight(QFont::Normal);
    oldCursor.mergeCharFormat(format);

    QTextCursor newCursor(textBlock);
    newCursor.select(QTextCursor::BlockUnderCursor);

    format.setFontWeight(QFont::Bold);
    newCursor.mergeCharFormat(format);

}
